<?php
/**
 * JoomlaZend
 * Zend Framework for Joomla
 * Red Black Tree LLC
 *
 *
 * @author rbsolutions (rbsoultions.us@gmail.com)
 * @copyright (c) 2010 Red Black Tree LLC
 * @category JoomlZend
 * @package ComZend-Chimpmail
 * @link http://joomlazend.rbsolutions.us
 * @version $Id:$
 */
defined ('_VALID_MOS') or
    die('Direct Access to this location is not allowed');
/**
 * Modules Subscriptions
 *
 * keeps a log of all of the subscription requests through the site
 *
 * @author rbsolutions (rbsoultions.us@gmail.com)
 * @copyright (c) 2010 Red Black Tree LLC
 * @category JoomlZend
 * @package ComZend-Chimpmail
 */
class Chimpmail_Model_Subscriptions extends Zend_Db_Table_Abstract
{
    /**
     * @var string Acceptance name of the table within the database
     */
    protected $_name = 'zf_chimpmail_subscriptions';
    /**
     * @var string name of the database to connect to
     */
    protected $_use_adapter = "joomla";
     /**
     * __construct
     *
     * queries the zend registry to select the proper database
     *
     * @param mixed $config
     * @return mixed
     */
    public function  __construct($config = null)
    {
        $this->_name = Zend_Registry::get('dbprefix') . $this->_name;
        if (isset($this->_use_adapter)) {
            $dbAdapters = Zend_Registry::get('dbAdapters');
            $config = ($dbAdapters[$this->_use_adapter]);
        }
        return parent::__construct($config);
    }
    /**
     * getName 
     * 
     * gets the name of the database table
     * 
     * @return string table name
     */
    public static function getName() {
        $mdl = new self();
        return $mdl->_name;
    }
    /**
     * getSubscription
     *
     * gets a record from the database
     *
     * @param int $id the unique id for the databse
     * @return Zend_db_Table_Row|NULL
     */
    public function getSubscription($id)
    {
        $mdl = $this;
        $resultSet = $mdl->find($id);
        if($resultSet->count() >0) {
            return $resultSet->current();
        }
        return NULL;
    }
    /**
     * createTable
     *
     * if the current table does not exists, create it
     */
    public function createTable()
    {
        try {
            $desc = $this->_db->describeTable($this->_name);
        } catch (exception $ex) {
            // table does not exist, create it
            $createSql = "CREATE TABLE `".$this->_name
                   ."` (id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, "
                   ."list_id TEXT NOT NULL DEFAULT '', "
                   ."web_id INT NOT NULL, "
                   ."first_name VARCHAR(255) NOT NULL DEFAULT '', "
                   ."last_name VARCHAR(255) NOT NULL DEFAULT '', "
                   ."email_address VARCHAR(255) NOT NULL DEFAULT '', "
                   ."created_on DATE, "
                   ."alt TEXT NOT NULL DEFAULT '', "
                   ."notes TEXT NOT NULL DEFAULT '', "
                   ."params TEXT)";
            $this->_db->query($createSql);
            $indexSQL = "CREATE INDEX `id` on `".$this->_name."` (`id`)";
            $this->_db->query($indexSQL);
        }
    }
    /**
     * removeTable
     *
     * removes the table from the database
     */
    public function removeTable()
    {
        $dropSql = "DROP TABLE IF EXISTS `".$this->_name."`";
        $this->_db->query($dropSql);
    }
    /**
     * getSelectArray
     *
     * gets an array designed to be used in a select box
     * @return array of program names
     */
    public function getSelectArray() {
        // initialize the array
        $array = array();
        // create the model
        $mdl = $this;
        // get a select
        $select = $mdl->select();
        // add conditions
        $select->order("last_name asc");
        // get the results
        $results = $mdl->fetchAll($select);
        // loop through to create the array
        foreach($results as $result) {
            $array[$result->id] = $result->name;
        }
        return $array;
    }
    /**
     * createSelectBox
     *
     * creates a select box for inclusion in a form
     */
    public static function createSelectBox($name) {
        // create the model
        $mdl = new self();
        //create the element
        $element = new Zend_Form_Element_Select($name);
        $element->setLabel("Person:")
                ->addMultiOption('',"(Select)")
                ->addMultiOptions($mdl->getSelectArray());
        return $element;
    }
    /**
     * addSubscription
     *
     * adds a new subscription to the database
     *
     * @param array $values
     * @return int
     */
    public function addSubscription(array $values)
    {
        try {
            $row = $this->createRow();
        } catch (Exception $ex) {
            $this->createTable();
            $row= $this->createRow();
        }        
        $row->created_on = date('Y-m-d');
        $id = $row->save();
        $this->updateSubscription($id, $values);
        return $row->save();
    }
    /**
     * updateSubscription
     *
     * updates a subscription in the database
     *
     * @param int $bannerId
     * @param array $values
     * @return int
     */
    public function updateSubscription ($id, array $values)
    {
        $row = $this->getSubscription($id);
        if($row==NULL) {
            throw new Exception("Error, could not find list to update:".$bannerId);
        }
        foreach($values as $name=>$val) {
            switch($name){
                case 'last_name':
                case 'first_name':
                case 'email_address':
                case 'list_id':
                case 'web_id':
                case 'alt':
                case 'params':
                case 'notes':
                    $row->$name=$val;
                    break;
                default:
                    break;
            }
        }
        return $row->save();
    }
    /**
     * deleteSubscription
     * 
     * delets a subscription from the database
     * 
     * @param int $banner
     * @return type 
     */
    public function deleteSubscription($id){
        $row = $this->getSubscription($id);
        if($row!= NULL) {
            return $row->delete();
        }
        return NULL;
    }
}

